/*
 * This software is intended to be a network InputMethod of android platform
 *
 * Copyright (c) 2014 Itleaks shen itleaks@126.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.fiberhome.opticalbox.common.kryonet;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.common.kryonet.RemoteInputService.LocalBinder;
import com.fiberhome.opticalbox.ui.keyboard810.MBaseRCActivity;
import com.fiberhome.opticalbox.utils.LogUtil;

public class RemoteInputActivity extends MBaseRCActivity {

	private EditText mInputView;
	private Handler mHandler = new Handler();
	private boolean isInputMethodShown = false;
	private Button btnFinish;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.ob_activity_input_main);
		super.onCreate(savedInstanceState);

		titleView.setTitle(R.string.ob_tv_input);
		titleView.setBackgroundColor(0xff454545);
		titleView.addLeftDrawableMenu(this, R.drawable.ob_ico_back, 15, 25, onBackClickListener);

		mInputView = (EditText) this.findViewById(R.id.input_text);
		String content = getIntent().getStringExtra(RemoteInputService.EXTRA_TEXTINFO);
		updateClientText(content);
		if (mInputView != null && !TextUtils.isEmpty(content)) {
			mInputView.setText(content);
		}
		mInputView.addTextChangedListener(new TextWatcher() {
			@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override public void afterTextChanged(Editable s) {
				syncTextToServer();
			}
		});

		btnFinish = (Button) findViewById(R.id.btn_finish);
		btnFinish.setOnClickListener(new View.OnClickListener() {
			@Override public void onClick(View v) {
				int back = getResources().getInteger(R.integer.ob_keycode_back);
				sendKey(back, MotionEvent.ACTION_DOWN);
				sendKey(back, MotionEvent.ACTION_UP);
				btnFinish.postDelayed(new Runnable() {
					@Override public void run() {
						int down = getResources().getInteger(R.integer.ob_keycode_down);
						sendKey(down, MotionEvent.ACTION_DOWN);
						sendKey(down, MotionEvent.ACTION_UP);
					}
				}, 500);
			}
		});

		bindInputService();
		registerInputbr();
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		unbindInputService();
		unregisterInputbr();

		hideKeyboard(mInputView);
	}

	private void syncTextToServer() {
		String text = mInputView.getText().toString();
		if (inputService == null) {
			LogUtil.e("empty input Service");
			return;
		}
		inputService.syncTextToServer(text);
	}

	private RemoteInputService inputService;

	private void bindInputService() {
		Intent intent = new Intent(this, RemoteInputService.class);
		bindService(intent, conn, Activity.BIND_AUTO_CREATE);
	}

	private void unbindInputService() {
		unbindService(conn);
	}

	private ServiceConnection conn = new ServiceConnection() {
		@Override public void onServiceDisconnected(ComponentName name) {
		}

		@Override public void onServiceConnected(ComponentName name, IBinder service) {
			inputService = ((LocalBinder) service).getService();
		}
	};

	private BroadcastReceiver inputbr = new BroadcastReceiver() {
		@Override public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (RemoteInputService.ACTION_KEY.equals(action)) {
				int key = Integer.valueOf(intent.getStringExtra(RemoteInputService.EXTRA_DATA));
				processKey(key);

			}
			else if (RemoteInputService.ACTION_TEXT.equals(action)) {
				String text = intent.getStringExtra(RemoteInputService.EXTRA_DATA);
				Log.d("RemoteIME", "BroadcastReceiver onReceive:" + text);
				updateClientText(text);
			}
		}
	};

	private void registerInputbr() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(RemoteInputService.ACTION_KEY);
		intentFilter.addAction(RemoteInputService.ACTION_TEXT);
		registerReceiver(inputbr, intentFilter);
	}

	private void unregisterInputbr() {
		unregisterReceiver(inputbr);
	}

	private void updateClientText(String text) {
		mInputView.setText(text);
		mInputView.setSelection(text.length());

		showKeyboard(mInputView);
	}

	private void processKey(int key) {
		if (KeyEvent.KEYCODE_BACK == key) {
			finish();
		}
	}

	private void hideKeyboard(View v) {
		if (isInputMethodShown) {
			InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm.isActive()) {
				imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
				isInputMethodShown = false;
			}
		}
	}

	private void showKeyboard(final View v) {
		if (!isInputMethodShown) {
			mHandler.postDelayed(new Runnable() {
				@Override public void run() {
					InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}, 200);
			isInputMethodShown = true;
		}
	}

}
